package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author GRS
 * @since 2024/4/19 下午7:48
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService
{
    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时插入菜品对应的口味数据
     */
    @Override
    @Transactional
    public void saveWithFlavors(DishDTO dishDTO)
    {
        // 保存菜品的基本信息到菜品表
        this.save(dishDTO);

        // 菜品ID
        Long dishId = dishDTO.getId();

        // 菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors = flavors
            .stream()
            .peek(item -> item.setDishId(dishId))
            .toList();

        // 保存菜品口味数据到菜品口味dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据ID查询菜品信息和对应的口味信息
     */
    @Override
    public DishDTO getByIdWithFlavors(Long id)
    {
        // 查询菜品基本信息， 从DISH表查询
        Dish dish = this.getById(id);
        DishDTO dishDTO = new DishDTO();

        BeanUtils.copyProperties(dish, dishDTO);

        // 查询当前菜品的口味信息，从DISH_FLAVOR表查询
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);
        dishDTO.setFlavors(flavors);
        return dishDTO;
    }

    /**
     * 更新菜品信息，同时更新对应的口味信息
     */
    @Override
    @Transactional
    public void updateWithFlavors(DishDTO dishDTO)
    {
        // 更新DISH表基本信息
        this.updateById(dishDTO);

        // 清理当前菜品对应的口味数据 ==> dish_flavor表的DELETE操作
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDTO.getId());
        dishFlavorService.remove(wrapper);

        // 添加当前提交过来的口味数据 ==> dish_flavor表的INSERT操作
        List<DishFlavor> flavors = dishDTO.getFlavors();

        flavors = flavors
            .stream()
            .peek(item -> item.setDishId(dishDTO.getId()))
            .toList();
        dishFlavorService.saveBatch(flavors);
    }
}